package com.hcloud.common.crud.controller;

import com.hcloud.common.core.annontion.BaseOperateLog;
import com.hcloud.common.core.base.HCloudResult;
import com.hcloud.common.core.constants.CoreContants;
import com.hcloud.common.core.constants.OperateType;
import com.hcloud.common.crud.annon.HCloudPreAuthorize;
import com.hcloud.common.crud.entity.BaseTreeEntity;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 公用的获取tree的方法，entity中必须有parentId且不为空
 * 调用基础的list获取数据后进行封装
 *
 * @Auther hepangui
 * @Date 2018/11/5
 */
public abstract class BaseTreeController<T extends BaseTreeEntity> extends BaseDataController<T> {


    @PostMapping("/tree")
    @HCloudPreAuthorize("see")
    @BaseOperateLog(type = OperateType.QUERY)
    public HCloudResult<BaseTreeEntity> tree(String sortProperties, String direction, T queryBean) {
        Integer page = null;
        Integer limit = null;
        HCloudResult hcloudResult = super.list(page, limit, sortProperties, direction, queryBean);
        List data = (List) hcloudResult.getData();
        if (data != null && data.size() > 0) {
            // list返回的为PO对象，转为VO对象
            List<T> treeBeans = this.buildTreeByRecursive(data);
            hcloudResult.setData(treeBeans);
        }
        return hcloudResult;
    }

    /**
     * 使用递归方法建树
     *
     * @param treeBeans
     * @return
     */
    public List<T> buildTreeByRecursive(Collection<T> treeBeans) {
        List<T> trees = new ArrayList<T>();
        for (T treeBean : treeBeans) {
            if (CoreContants.TREE_ROOT.equals(treeBean.getParentId())) {
                trees.add(findChildren(treeBean, treeBeans));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeBeans
     * @return
     */
    public T findChildren(T treeNode, Collection<T> treeBeans) {
        treeNode.setChildren(new ArrayList<>());
        for (T treeBean : treeBeans) {
            if (treeNode.getId().equals(treeBean.getParentId())) {
//                if (treeNode.getChildren() == null) {
//                    treeNode.setChildren(new ArrayList<>());
//                }
                treeNode.getChildren().add(findChildren(treeBean, treeBeans));
            }
        }
        return treeNode;
    }

}
